package com.digital.herbarium.Entity;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.digital.herbarium.Util.HttpUtils;
import com.digital.herbarium.Util.TimeUtil;
import com.digital.herbarium.annotation.Log;
import com.digital.herbarium.service.LoggerService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Aspect
@Component
public class LogAspect {
    @Autowired
    LoggerService loggerService;

    @Pointcut("@annotation(com.digital.herbarium.annotation.Log)")
    public void pointCut() {}

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getName();
        Object[] args = joinPoint.getArgs();

        // 获取@Log注解的值
        MethodSignature signature = null;
        if (joinPoint.getSignature() instanceof MethodSignature) {
            signature = (MethodSignature) joinPoint.getSignature();
        } else {
            return;
        }

        Method method = signature.getMethod();
        Log logAnnotation = method.getAnnotation(Log.class);
        String operation = logAnnotation.value();

        // 获取当前用户
//        String username = SecurityContextHolder.getContext().getAuthentication().getName();

        // 获取请求参数
        JSONObject params = null;
        if (args.length > 0) {
            String str = JSON.toJSONString(args[0]);
            params = JSON.parseObject(str);
        }

        // 获取请求IP
        String ip = HttpUtils.getIpAddr(request);

        // 记录日志
        List<Logger> llist = new ArrayList<>();
        if(params != null){
            params.forEach((key, value) -> {
                if (!StrUtil.hasEmpty(value.toString()) && !StrUtil.hasBlank(value.toString())) {
                    if(!value.toString().equals("0")){
                        Logger log = new Logger();
                        log.setOperation(operation);
                        log.setMethod(className + "." + methodName + "()");
                        log.setParams(value.toString());
                        log.setIp(ip);
                        log.setCreateTime(TimeUtil.getNow());
                        llist.add(log);
                    }


                }
            });
            if(llist != null &&  llist.size() > 0){
                loggerService.save(llist);
            }

        }


    }
}